import Taro from "@tarojs/taro"

function locate(success: IFn, fail: IFn) {
  wx.getFuzzyLocation({
    type: "gcj02",
    success(result) {
      console.log("getLocation", result)
      success(result)
    },
    fail: err => {
      console.log("Taro.getLocation--error", err)
      Taro.showToast({
        title: "获取定位失败,请检查位置授权是否开启",
        icon: "none"
      })
      fail(err)
    }
  })
}
function getPositionMap(result, resolve, reject) {
  Taro.showLoading({
    title: "定位中..."
  })
  Taro.request({
    url:
      `https://apis.map.qq.com/ws/geocoder/v1/?key=CYNBZ-LKIKX-4SG4W-Z7LUL-VR5AH-AOFFH&get_poi=0&location=` +
      result.latitude +
      "," +
      result.longitude,
    success: res => {
      console.log("getPositionMap apis--res", res) // 此处返回的就是需要查询的城市名称
      const retData = res.data.result
      if (retData) {
        const cityName = retData.address_component.city
        const province = retData.address_component.province
        const ret: IGetPositionRet = {
          lat: result.latitude,
          lng: result.longitude,
          cityName,
          mapType: 2,
          province
        }
        locateTip("定位成功")
        resolve(ret)
      } else {
        locateTip("定位失败")
        reject()
      }
    },
    fail: reject
  })
}
function locateTip(title: string) {
  Taro.hideLoading()
  Taro.showToast({
    title,
    icon: "none"
  })
}
export const getPosition = () => {
  return new Promise((resolve, reject) => {
    function onSuccess(result) {
      getPositionMap(result, resolve, reject)
    }
    Taro.authorize({
      scope: "scope.userFuzzyLocation",
      success() {
        locate(onSuccess, reject)
      },
      fail() {
        Taro.showModal({
          title: "提示",
          content: "拒绝授权位置可能会导致部分小程序功能受限, 打开授权？",
          success(result) {
            if (result.confirm) {
              Taro.openSetting({
                success({ authSetting }) {
                  if (authSetting["scope.userFuzzyLocation"]) {
                    locate(onSuccess, reject)
                  } else {
                    locateTip("定位失败")
                    reject()
                  }
                }
              })
            } else {
              console.log("拒绝 了")
              locateTip("定位失败")
              reject()
            }
          }
        })
      }
    })
  })
}
